# -*- coding: utf-8 -*-
"""
固定资产管理系统 - 自定义Admin界面配置
"""

from django.contrib import admin
from django.urls import path
from django.http import JsonResponse
from django.db.models import Count
from django.utils import timezone


class CustomAdminSite(admin.AdminSite):
    """自定义Admin站点"""
    
    site_header = "固定资产管理系统5.0"
    site_title = "资产管理"
    index_title = "管理控制台"
    
    def get_urls(self):
        """添加自定义URL"""
        urls = super().get_urls()
        custom_urls = [
            path('dashboard-stats/', self.dashboard_stats_view, name='dashboard_stats'),
            path('asset-chart-data/', self.asset_chart_data_view, name='asset_chart_data'),
        ]
        return custom_urls + urls
    
    def dashboard_stats_view(self, request):
        """仪表板统计数据API"""
        try:
            from assets.models import Asset, AssetBorrow
            
            # 资产统计
            total_assets = Asset.objects.count()
            active_assets = Asset.objects.filter(status='active').count()
            
            # 借用统计
            current_borrows = AssetBorrow.objects.filter(status='borrowed').count()
            
            data = {
                'assets': {
                    'total': total_assets,
                    'active': active_assets,
                },
                'borrows': {
                    'current': current_borrows,
                }
            }
            
            return JsonResponse(data)
        except Exception as e:
            return JsonResponse({'error': str(e)}, status=500)
    
    def asset_chart_data_view(self, request):
        """资产图表数据API"""
        try:
            from assets.models import Asset, AssetCategory
            
            # 按类别统计
            category_stats = AssetCategory.objects.annotate(
                asset_count=Count('asset')
            ).values('name', 'asset_count')
            
            data = {
                'category_stats': list(category_stats),
            }
            
            return JsonResponse(data)
        except Exception as e:
            return JsonResponse({'error': str(e)}, status=500)


# 创建自定义admin站点实例
custom_admin_site = CustomAdminSite(name='custom_admin')